package com.mrs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mrs.common.constants.SystemConstants;
import com.mrs.entity.LoginUser;
import com.mrs.entity.User;
import com.mrs.mapper.MenuMapper;
import com.mrs.mapper.UserMapper;
import com.mrs.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * description: UserDetailsServiceImpl
 * date: 2022/8/7 22:24
 * author: MR.孙
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查看用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(queryWrapper);
        //判断是否查到用户,如果没有查到用户就抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }


        //返回用户信息
        //TODO 查询权限信息封装
        //TODO 只有是后台用户才需要权限的封装
        if(user.getType().equals(SystemConstants.ADMIN)){
            //查询当前用户权限列表
            List<String> permissions = menuMapper.selectPermissions(user.getId());
            return new LoginUser(user, permissions);
        }

        //不是后台用户，不需要返回权限列表
        return new LoginUser(user, null);
    }
}
